import { useState } from 'react';
import { toast } from 'sonner';
import AdminLayout from '@/components/admin/AdminLayout';
import ImageUpload from '@/components/common/ImageUpload';
import { useBanners, useCreateBanner, useUpdateBanner, useDeleteBanner } from '@/hooks/useBanners';
import { Banner, BannerCreate, BannerUpdate } from '@/types';
import { cn } from '@/lib/utils';



export default function BannerManagement() {
  // API hooks
  const { data: bannersData, isLoading, error } = useBanners();
  const createBannerMutation = useCreateBanner();
  const updateBannerMutation = useUpdateBanner();
  const deleteBannerMutation = useDeleteBanner();

  // 状态管理
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentBanner, setCurrentBanner] = useState<Banner | null>(null);
  const [isEditing, setIsEditing] = useState(false);

  // 表单状态
  const [formData, setFormData] = useState({
    title: '',
    subtitle: '',
    image_url: '',
    is_active: true
  });

  const banners = bannersData?.items || [];
  
  // 打开添加轮播图模态框
  const openAddModal = () => {
    setIsEditing(false);
    setCurrentBanner(null);
    setFormData({
      title: '',
      subtitle: '',
      image_url: '',
      is_active: true
    });
    setIsModalOpen(true);
  };

  // 打开编辑轮播图模态框
  const openEditModal = (banner: Banner) => {
    setIsEditing(true);
    setCurrentBanner(banner);
    setFormData({
      title: banner.title,
      subtitle: banner.subtitle || '',
      image_url: banner.image_url,
      is_active: banner.is_active
    });
    setIsModalOpen(true);
  };
  
  // 关闭模态框
  const closeModal = () => {  
    setIsModalOpen(false);
  };
  
  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };
  
  // 处理图片上传成功
  const handleImageUpload = (url: string) => {
    setFormData(prev => ({
      ...prev,
      image_url: url
    }));
  };

  // 处理图片上传错误
  const handleImageUploadError = (error: string) => {
    toast.error(error);
  };
  
  // 保存轮播图（添加或编辑）
  const saveBanner = async () => {
    if (!formData.title || !formData.image_url) {
      toast.error('请填写所有必填字段');
      return;
    }

    try {
      if (isEditing && currentBanner) {
        // 编辑现有轮播图
        const updateData: BannerUpdate = {
          title: formData.title,
          subtitle: formData.subtitle,
          image_url: formData.image_url,
          is_active: formData.is_active
        };

        await updateBannerMutation.mutateAsync({
          id: currentBanner.id,
          data: updateData
        });

        toast.success('轮播图更新成功');
      } else {
        // 添加新轮播图
        const createData: BannerCreate = {
          title: formData.title,
          subtitle: formData.subtitle,
          image_url: formData.image_url,
          is_active: formData.is_active
        };

        await createBannerMutation.mutateAsync(createData);
        toast.success('轮播图创建成功');
      }

      closeModal();
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '操作失败');
    }
  };

  // 删除轮播图
  const deleteBanner = async (id: number) => {
    if (window.confirm('确定要删除这个轮播图吗？')) {
      try {
        await deleteBannerMutation.mutateAsync(id);
        toast.success('轮播图删除成功');
      } catch (error: any) {
        toast.error(error.response?.data?.detail || '删除失败');
      }
    }
  };

  // 切换轮播图状态
  const toggleBannerStatus = async (id: number) => {
    const banner = banners.find(b => b.id === id);
    if (!banner) return;

    try {
      const updateData: BannerUpdate = {
        title: banner.title,
        subtitle: banner.subtitle,
        image_url: banner.image_url,
        is_active: !banner.is_active
      };

      await updateBannerMutation.mutateAsync({
        id,
        data: updateData
      });

      toast.success('轮播图状态已更新');
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '更新失败');
    }
  };
  
  if (isLoading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[500px]">
          <div className="text-center">
            <i className="fa-solid fa-spinner fa-spin text-3xl text-blue-600 mb-4"></i>
            <p className="text-gray-600">加载中...</p>
          </div>
        </div>
      </AdminLayout>
    );
  }

  if (error) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[500px]">
          <div className="text-center">
            <i className="fa-solid fa-exclamation-triangle text-3xl text-red-600 mb-4"></i>
            <p className="text-gray-600">加载轮播图数据失败</p>
            <p className="text-sm text-gray-500 mt-2">{error.message}</p>
          </div>
        </div>
      </AdminLayout>
    );
  }
  
  return (
    <AdminLayout>
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-800">轮播图管理</h1>
          <p className="text-gray-600">管理首页轮播图内容</p>
        </div>
        <button
          onClick={openAddModal}
          className="mt-4 md:mt-0 bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition-colors flex items-center"
        >
          <i className="fa-solid fa-plus mr-2"></i> 添加轮播图
        </button>
      </div>
      
      {/* 轮播图列表 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">图片</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">副标题</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {banners.length > 0 ? (
                banners.map((banner) => (
                  <tr key={banner.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{banner.id}</td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="w-32 h-16 rounded overflow-hidden">
                        <img
                          src={banner.image_url}
                          alt={banner.title}
                          className="w-full h-full object-cover"
                        />
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{banner.title}</td>
                    <td className="px-6 py-4 text-sm text-gray-500 max-w-xs">{banner.subtitle || '-'}</td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span
                        className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                          banner.is_active
                            ? 'bg-green-100 text-green-800'
                            : 'bg-gray-100 text-gray-800'
                        }`}
                      >
                        {banner.is_active ? '启用' : '禁用'}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{banner.created_at}</td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <button
                        onClick={() => toggleBannerStatus(banner.id)}
                        className={`mr-3 text-sm ${
                          banner.is_active
                            ? 'text-yellow-600 hover:text-yellow-900'
                            : 'text-green-600 hover:text-green-900'
                        }`}
                      >
                        {banner.is_active ? '禁用' : '启用'}
                      </button>
                      <button
                        onClick={() => openEditModal(banner)}
                        className="text-blue-600 hover:text-blue-900 mr-3 text-sm"
                      >
                        编辑
                      </button>
                      <button
                        onClick={() => deleteBanner(banner.id)}
                        className="text-red-600 hover:text-red-900 text-sm"
                      >
                        删除
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={7} className="px-6 py-10 text-center text-gray-500">
                    <div className="flex flex-col items-center">
                      <i className="fa-solid fa-images text-4xl mb-3 text-gray-300"></i>
                      <p>暂无轮播图数据</p>
                      <button
                        onClick={openAddModal}
                        className="mt-2 text-blue-600 hover:text-blue-900 text-sm"
                      >
                        添加轮播图
                      </button>
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
      
      {/* 轮播图添加/编辑模态框 */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-xl shadow-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-bold text-gray-800">{isEditing ? '编辑轮播图' : '添加轮播图'}</h3>
                <button
                  onClick={closeModal}
                  className="text-gray-500 hover:text-gray-700"
                >
                  <i className="fa-solid fa-times"></i>
                </button>
              </div>
            </div>
            
            <div className="p-6">
              <form>
                <div className="mb-6">
                  <label htmlFor="title" className="block text-gray-700 font-medium mb-2">
                    标题 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    id="title"
                    name="title"
                    value={formData.title}
                    onChange={handleInputChange}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                    placeholder="请输入轮播图标题"
                  />
                </div>
                
                <div className="mb-6">
                  <label htmlFor="subtitle" className="block text-gray-700 font-medium mb-2">
                    副标题
                  </label>
                  <textarea
                    id="subtitle"
                    name="subtitle"
                    value={formData.subtitle}
                    onChange={handleInputChange}
                    rows={3}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                    placeholder="请输入轮播图副标题"
                  ></textarea>
                </div>
                
                <div className="mb-6">
                  <label className="block text-gray-700 font-medium mb-2">
                    图片 <span className="text-red-500">*</span>
                  </label>
                  <ImageUpload
                    value={formData.image_url}
                    onChange={handleImageUpload}
                    onError={handleImageUploadError}
                    width={320}
                    height={160}
                    maxSize={5}
                    placeholder="点击或拖拽上传轮播图"
                    autoCompress={true}
                  />
                  <p className="text-xs text-gray-500 mt-2">
                    建议尺寸: 1920x500px，支持 JPG、PNG、WebP 格式，最大 5MB
                  </p>
                </div>
                
                <div className="mb-6">
                  <label className="flex items-center">
                    <input
                      type="checkbox"
                      name="is_active"
                      checked={formData.is_active}
                      onChange={handleInputChange}
                      className="form-checkbox h-5 w-5 text-blue-600 rounded"
                    />
                    <span className="ml-2 text-gray-700">启用轮播图</span>
                  </label>
                </div>
              </form>
            </div>
            
            <div className="p-6 border-t flex justify-end space-x-3">
              <button
                onClick={closeModal}
                className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
              >
                取消
              </button>
              <button
                onClick={saveBanner}
                className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
              >
                {isEditing ? '更新轮播图' : '添加轮播图'}
              </button>
            </div>
          </div>
        </div>
      )}
    </AdminLayout>
  );
}
